import { createRouter, createWebHashHistory } from "vue-router";
import useUserStore from "@/stores/modules/user";
import { addDynamicRoutes } from "@/router/modules/addDynamicRouter";
import NProgress from "nprogress";
import { routerWhiteList } from "@/enum/index";

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "layout",
      component: () => import("@/layout/index.vue"),
      redirect: "/home/index",
      children: []
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/index.vue"),
      meta: {
        title: "登录页"
      }
    },
    {
      path: "/protocol",
      name: "protocol",
      component: () => import("@/views/protocol/index.vue"),
      meta: {
        title: "协议页"
      }
    },
    {
      path: "/:pathMatch(.*)*",
      name: "404",
      component: () => import("@/views/404/index.vue")
    },
    {
      path: "/QRCodePage/:id",
      name: "QRCodePage",
      component: () => import("@/views/QRCodePage/index.vue"),
      meta: {
        title: "二级维护信息"
      }
    }
  ],
  scrollBehavior: () => ({ left: 0, top: 0 })
});

// 全局前置路由导航守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const userStore = useUserStore();
  // 设置页面标题
  document.title = import.meta.env.VITE_TITLE;
  // 是否在白名单
  if (routerWhiteList.includes(to.path)) return next();
  // 是否有 Token
  if (userStore.token) {
    if (to.path === "/login" || to.path === "/QRCodePage") {
      next({ path: "/" });
    } else {
      // 获取菜单列表
      if (!userStore.menuList.length) {
        await addDynamicRoutes();
        next({ path: to.path });
      } else {
        next();
      }
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
export default router;
